from iClouds.allSerializers import *
from .Serializers import *
# Create your views here.


class AllinpayWxchatPosViewSet(viewsets.ModelViewSet):
    __title__ = '微信商户名单信息'
    __group__ = '微信商户'
    __info__ = {'get': '查询AI爱好标签列表', 'post': '创建AI爱好标签',
                'put': '编辑AI爱好标签', 'patch': '编辑AI爱好标签', 'delete': '移除AI爱好标签'}
    __doc__ = '''
    list:
    <h4>AI爱好标签列表</h4>
    retrieve:
    <h4>AI爱好标签详情</h4>
    create:
    <h4>创建AI爱好标签</h4>
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>移除AI爱好标签</h4>'''
    http_method_names = ['get']
    authentication_classes = [] if settings.DEBUG else [AdminJWTAuthentication]
    permission_classes = [
        AllPermissions] if settings.DEBUG else [AdminPermissions]
    serializer_class = AllinpayWxchatPosSerializer
    queryset = AllinpayWxchatPos.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['parent', 'lte']
    # search_fields = ['phone','email']
    ordering_fields = 'id'

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response({'rescode': 200, 'resmsg': serializer.data, 'count': c, 'size': self.pagination_class.page_size})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({'rescode': 200, 'resmsg': serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'rescode': 200, 'resmsg': serializer.data})

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(
            instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'rescode': 200, 'resmsg': serializer.data})

    def partial_update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(
            instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'rescode': 200, 'resmsg': serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({'rescode': 200, 'resmsg': 'SUCCESS'})


class AllinpayWxpayListViewSet(viewsets.ModelViewSet):
    __title__ = '微信收单资费套餐'
    __group__ = '微信商户'
    __info__ = {
        'get': '查询收单资费套餐',
        'post': '创建收单资费套餐',
        'put': '编辑收单资费套餐',
        'patch': '编辑收单资费套餐',
        'delete': '移除收单资费套餐'}
    __doc__ = '''
    list:
    <h4>收单资费套餐列表</h4>
    retrieve:
    <h4>变更当前费率</h4>
        header["name"] = "aniPortrait"
        将当前费率变更为：{id}
    create:
    <h4>创建收单资费套餐</h4>
        header["name"] = "aniPortrait"
    update:
    <h4>编辑收单资费套餐</h4>
        header["name"] = "aniPortrait"
    partial_update:
    <h4>编辑收单资费套餐</h4>
        header["name"] = "aniPortrait"
    delete:
    <h4>移除收单资费套餐</h4>
        header["name"] = "aniPortrait"
    '''

    http_method_names = ['get', 'post', 'put', 'delete']
    authentication_classes = []
    permission_classes = [AllPermissions]
    pagination_class = StandardPagination
    versioning_class = MyDefaultVersioning
    serializer_class = AllinpayWxpayListSerializer
    queryset = AllinpayWxpayList.objects.all().order_by('-id')

    # filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['status']
    # search_fields = ['phone','email']
    # ordering_fields = ['-id',]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response({'rescode': 200, 'resmsg': serializer.data, 'count': c, 'size': self.pagination_class.page_size, "current": self.hasCurrentSet()})

    def retrieve(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        AllinpayWxpayCurl.objects.filter(id=1).update(
            **{"cur": instance.id, "lasttime": timezone.now()})
        return Response({'rescode': 200, 'resmsg': serializer.data, "current": self.hasCurrentSet()})

    def create(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now())
        return Response({'rescode': 200, 'resmsg': serializer.data})

    def update(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        instance = self.get_object()
        serializer = self.get_serializer(
            instance, data=request.data, partial=False)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now())
        return Response({'rescode': 200, 'resmsg': serializer.data})

    def destroy(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        instance = self.get_object()
        if self.hasCurrentSet() == instance.id:
            raise ValidationError("当前费率使用中")
        self.perform_destroy(instance)
        return Response({'rescode': 200, 'resmsg': 'SUCCESS'})

    def hasCurrentSet(self):
        '''查询当前费率'''
        try:
            r = AllinpayWxpayCurl.objects.get(id=1)
        except BaseException as err:
            raise ValidationError("查询当前费率失败")
        else:
            return r.cur


# 检查视图
filter_views(globals())
